//app.js
var handler=require("utils/function.js");
// 播放器
const innerAudioContext = wx.createInnerAudioContext();
innerAudioContext.obeyMuteSwitch = false;
/**
 * 录音播放
 * @param src 音频地址
 * @param duration 音频秒数（单位 S）
 */
let SoundRecordingPlay = function ({ src, duration }) {
  let _src = src;
  let _duration = duration;
  if (_src && _duration) {
    innerAudioContext.src = _src
    innerAudioContext.play();
    // setTimeout(function () {
    //   innerAudioContext.stop();
    // }, _duration * 1000)
  } 
}
App({
    api: require("api.js"),
    siteInfo: require("siteinfo.js"),
    
    webRoot: null,
    currentPage: null,
    is_binding: 0,
    setApi: function() {
        var o = this.siteInfo.siteroot;
        o = o.replace("app/index.php", ""), o += "addons/sd_drviing/core/api.php/?s=",
            this.api = function t(e) {
                for (var a in e) "string" == typeof e[a] ? e[a] = e[a].replace("{$_api_root}", o) : e[a] = t(e[a]);
                return e;
            }(this.api);
        var t = this.api.default.index,
            e = t.substr(0, t.indexOf("/api.php"));
        this.webRoot = e;
    },
    onLaunch: function() {
        this.setApi();
       // this.getUserInfo();
        // 获取用户信息
        wx.getSetting({
            success: res => {
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                        success: res => {
                            // 可以将 res 发送给后台解码出 unionId
                            this.globalData.userInfo = res.userInfo
                            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                            // 所以此处加入 callback 以防止这种情况
                            if (this.userInfoReadyCallback) {
                                this.userInfoReadyCallback(res)
                            }
                        }
                    })
                }
            }
        })
        var that = this;
        // 调用用户的地理位置
        handler.getLatLntHandler(()=>{
          
        });
         //循环间隔 单位ms
      setInterval(function () {
        that.getdlocation();
      }, 10000)
    },
    getUserInfo: function(cb) {
        wx.getUserInfo({
            success: res => {
                // 登录
                wx.login({
                    success: re => {
                        // 发送 res.code 到后台换取 openId, sessionKey, unionId
                        this.request({
                            url: this.api.user.login,
                            method: 'post',
                            data: {
                                code: re.code,
                                iv: res.iv,
                                encryptedData: res.encryptedData
                            },
                            success: function(rs) {
                                //获取到用户详细信息
                                if (rs.code == 1) {
                                    this.is_binding = rs.data.is_binding;
                                    wx.setStorageSync("access_token", rs.data.access_token);
                                    wx.setStorageSync("serverphone", rs.data.serverphone);

                                    if (rs.data.type == 1 && rs.data.audit == 1 && rs.data.status == 1) {
                                        wx.reLaunch({
                                            url: '../../index/index'
                                        })
                                    }
                                    //保存数据 用来判断是否绑定手机号
                                    wx.setStorageSync('is_binding', rs.data.is_binding)
                                }
                            }
                        })
                    }
                })
            }
        })
    },
    // 获取用户的地理位置
    getlocation: function() {
        // console.log(cb)
        const that = this;
        wx.getLocation({
            type: 'gcj02',
            success: function(res) {
                var latitude = res.latitude
                var longitude = res.longitude
                var speed = res.speed
                var accuracy = res.accuracy
                var locationString = res.latitude + "," + res.longitude; //获取的经度纬度
                wx.request({
                    url: 'http://apis.map.qq.com/ws/geocoder/v1/?l&get_poi=1', //根据经纬度转换成具体地址
                    data: {
                        "key": "YLFBZ-WHAWI-ZXUGH-53Q65-TOJ7E-ADBNQ",
                        "location": locationString
                    },
                    method: 'GET',
                    // header: {},
                    success: function(res) {
                        wx.setStorageSync("startAddress", {
                            title: res.data.result.address,
                            address: res.data.result.address,
                            location: {
                                lat: latitude,
                                lng: longitude
                            }
                        });
                        if (wx.getStorageSync("userMessage") != '') {
                            that.request({
                                url: that.api.real_time.add,
                                method: 'post',
                                data: {
                                    lat: latitude,
                                    lng: longitude
                                },
                                success: function(rs) {
                                    wx.setStorageSync("positioning", rs.data);
                                }
                            })
                        }
                    },
                    fail: function() {
                        // fail
                        console.log("请求失败");
                    },
                    complete: function(rs) {
                        // complete
                        console.log("请求完成", rs);
                    }
                })
            }
        })
    },
    getdlocation: function() {
        const that = this;
        if (wx.getStorageSync("userMessage") != '') {
            wx.getLocation({
                type: 'gcj02',
                success: function(res) {
                    var latitude = res.latitude
                    var longitude = res.longitude
                    var speed = res.speed
                    var accuracy = res.accuracy
                    var locationString = res.latitude + "," + res.longitude; //获取的经度纬度
                    that.request({
                        url: that.api.real_time.add,
                        method: 'post',
                        data: {
                            lat: latitude,
                            lng: longitude
                        },
                        success: function(rs) {
                          if (rs.data.type==1){
                            if (rs.data.new_order==1){
                              new SoundRecordingPlay({ src: '/we7/resource/video/alert.mp3', duration: "14" });
                            }
                          }
                            wx.setStorageSync("positioning", rs.data);
                        }
                    })
                }
            })
        }
    },
    /*    getDataHnadler: function() {
            const datas = require("./data/driverMockData.js");
            const {
                driver,
                order,
                activity,
                award,
                evaluate,
                knowledge,
                server_phone
            } = datas.data;
            console.log({
                driver,
                order,
                activity,
                award,
                evaluate,
                knowledge
            });
            wx.setStorageSync("driver", driver);
            wx.setStorageSync("order", order);
            wx.setStorageSync("knowledge", knowledge);
            wx.setStorageSync("award", award);
            wx.setStorageSync("activity", activity);
            wx.setStorageSync("evaluate", evaluate);
            wx.setStorageSync("setup", {
                "listenWay": "抢单模式",
                "orderHobby": "全部",
                "orderDistance": 1
            });
            wx.setStorageSync("server_phone", server_phone);
        },*/
    request: function(a) {
        a.data || (a.data = {});
        var t = wx.getStorageSync("access_token");
        t && (a.data.access_token = t), a.data._uniacid = this.siteInfo.uniacid, a.data._acid = this.siteInfo.acid,
            wx.request({
                url: a.url,
                header: a.header || {
                    "content-type": "application/x-www-form-urlencoded"
                },
                data: a.data || {},
                method: a.method || "GET",
                dataType: a.dataType || "json",
                success: function(t) {
                    if (t.data.code == -100) {
                        wx.showModal({
                            title: '提示',
                            content: '小程序应用未注册，请联系开发者',
                            showCancel: false
                        })
                    } - 1 == t.data.code ? '' : a.success && a.success(t.data);
                },
                fail: function(t) {
                    console.warn("--- request fail >>>"), console.warn(t), console.warn("<<< request fail ---");
                    var e = getApp();
                    e.is_on_launch ? (e.is_on_launch = !1, wx.showModal({
                        title: "",
                        content: t.errMsg,
                        showCancel: !1,
                        success: function(t) {
                            t.confirm && a.fail && a.fail(t);
                        }
                    })) : ('', a.fail && a.fail(t));
                },
                complete: function(t) {
                    200 != t.statusCode && (console.log("--- request http error >>>"), console.log(t.statusCode), console.log(t.data), console.log("<<< request http error ---")), a.complete && a.complete(t);
                }
            });
    },
    globalData: {
        userInfo: null
    }
})